using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Services
{
    public class TokenizerLocatorService : ITokenizerLocatorService
    {
        private readonly ILogger<TokenizerLocatorService> _logger;

        public TokenizerLocatorService(ILogger<TokenizerLocatorService> logger)
        {
            _logger = logger;
        }

        public async Task<string?> EnsureTokenizerAsync(RWKVConfig config, string modelPath)
        {
            try
            {
                // 1) 如果配置中已有有效 tokenizer，直接返回
                if (!string.IsNullOrWhiteSpace(config.LocalTokenizerPath) && File.Exists(config.LocalTokenizerPath))
                {
                    return config.LocalTokenizerPath;
                }

                // 2) 尝试在模型同目录查找常见文件名
                var dir = Path.GetDirectoryName(modelPath) ?? Environment.CurrentDirectory;
                var candidates = new[] { "tokenizer.json", "20B_tokenizer.json", "rwkv_tokenizer.json" }
                    .Select(f => Path.Combine(dir, f)).ToList();
                var found = candidates.FirstOrDefault(File.Exists);
                if (found != null)
                {
                    config.LocalTokenizerPath = found;
                    return found;
                }

                // 3) 尝试从用户提供的 RWKV Python 目录获取（固定路径，用户需求）
                //    G:\RWKV\backend-python\rwkv_pip\
                var builtinDir = @"G:\RWKV\backend-python\rwkv_pip";
                if (Directory.Exists(builtinDir))
                {
                    var all = Directory.EnumerateFiles(builtinDir, "*tokenizer*.json", SearchOption.AllDirectories)
                        .Concat(Directory.EnumerateFiles(builtinDir, "tokenizer.json", SearchOption.AllDirectories))
                        .Concat(Directory.EnumerateFiles(builtinDir, "20B_tokenizer.json", SearchOption.AllDirectories))
                        .Distinct()
                        .ToList();
                    var pick = all.FirstOrDefault();
                    if (pick != null && File.Exists(pick))
                    {
                        // 复制到应用数据目录，避免跨盘引用带来权限或移动风险
                        var targetDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                            "DocumentCreationSystem", "tokenizers");
                        Directory.CreateDirectory(targetDir);
                        var targetPath = Path.Combine(targetDir, Path.GetFileName(pick));
                        File.Copy(pick, targetPath, overwrite: true);
                        config.LocalTokenizerPath = targetPath;
                        _logger.LogInformation("已从内置路径复制 tokenizer 到: {Path}", targetPath);
                        return targetPath;
                    }
                }

                // 4) 未找到，返回 null
                _logger.LogWarning("未能定位到 tokenizer 文件，请在设置中手动指定");
                return null;
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "定位 tokenizer 失败");
                return null;
            }
            finally
            {
                await Task.CompletedTask;
            }
        }
    }
}

